<?php
namespace app\index\controller;
use app\index\controller\Basewx;
use app\service\apiService;
use app\service\orderService;
use app\service\invoiceService;
use think\Controller;
use think\request;
use think\Db;
use think\facade\Log;
class H5wxpay extends Basewx{
    public function index(){
        $gateid=request()->get("gateid");
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3fd7e9c4152f4823&redirect_uri=https://www.aliwgzf.com/index/h5wxpay/gatepay?gateid=".$gateid."&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        //echo $url;die;
        header("Location:".$url);
		exit;
    }
    public function test(){
        $code = request()->get('code');
        echo $code;die;
		$appid="wx3fd7e9c4152f4823";
		$secret="dfc5e75de83b93d8abb1d41aeced2a72"; 
		//用通过code换取网页授权access_token，同时获得openid
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
		$userinfo=$this->getJson($url);
		var_dump($userinfo);die;
		if(!empty($userinfo['errmsg'])){
            return $userinfo['errmsg'];
        }
        
        $this->assign("user_id",$userinfo['openid']);
    }
    public function gatepay(){
        
        $gateid=request()->get("gateid");
        $gateinfo=Db::table("parking_gatepay")->where("id",$gateid)->find();
        $this->assign("gateinfo",$gateinfo);

        $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$gateinfo["parkingNo"])->find();
        $communityinfo=Db::table("community")->where("id",$parkinginfo["community_id"])->find();
        $merchant_name = Db::name('property')->where('id',$communityinfo["property_id"])->value('merchant_name');
        $this->assign("merchant_name",$merchant_name);
        return $this->fetch();
    }
    
    
    public function gatepayOrder(){
        $gateid=request()->post("gateid");
	    $gateinfo=Db::table("parking_gatepay")->where("id",$gateid)->find();//$gateinfo["parkingNo"]
	    $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$gateinfo["parkingNo"])->find();
	    $communityinfo=Db::table("community")->where("id",$parkinginfo["community_id"])->find();
	    $invoiceinfo=(new invoiceService())->parkingInvoice($gateinfo["parkingNo"]);;
        $info["gateid"]=$gateinfo["id"];
        $info["parkingNo"]=$parkinginfo["parkingNo"];
        $info["parkingName"]=$parkinginfo["parkingName"];
       
        $info["gateName"]=$gateinfo["gateName"];
		$info["user_id"]=session("user_id");
        $info["order_money"]=request()->post("pay_money");
        $info["remark"]=request()->post("remark");
		$info["pay_money"]=request()->post("pay_money");
		$info["out_trade_no"]=date('YmdHiss').rand(100000,999999);
        $info["subject"] =$gateinfo["gateName"];
			//生成订单
		$data['appid'] = "wx3fd7e9c4152f4823";//公众账号ID
		$data['mch_id'] ="1484539292";//
		//根据停车场商户ID
		$data['sub_mch_id'] =(new orderService())->getmchid($info["parkingNo"]);
		$data['nonce_str'] = $this->createNoncestr();//随机字符串
		$data['body'] = $gateinfo["gateName"];//商品描述
		$data['out_trade_no'] = $info["out_trade_no"];//商户订单号
		$data['total_fee'] = $info["order_money"]*100;//总金额
		//$data['total_fee']=1;
		$data['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
		$data['notify_url'] = 'http://www.aliwgzf.com/index/callback/gatewxnotice';//通知url
		$data['trade_type'] = 'JSAPI';
		$data['openid'] = $info["user_id"];//用户标识
		
		$wxkey="asdfaASDFASDFASFasfsadf6546A84SA";
		$data['sign'] = $this->MakeSign($data,$wxkey);//签名
		// return json(['info' => $data]);
		//输出xml字符
		
		$xml = $this->ToXml($data);
		
		$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		//CURL模拟请求
		$curls = curl_init(); //启动一个CURL会话
		curl_setopt($curls, CURLOPT_URL, $url); //要访问的地址
		curl_setopt($curls, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curls, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curls, CURLOPT_HEADER, FALSE);//设置header
		curl_setopt($curls, CURLOPT_RETURNTRANSFER, TRUE);//要求结果为字符串且输出到屏幕上
		curl_setopt($curls, CURLOPT_POST, TRUE); //发送一个常规的Post请求
		curl_setopt($curls, CURLOPT_POSTFIELDS, $xml); //Post提交的数据包
		curl_setopt($curls, CURLOPT_TIMEOUT, 30); //设置超时限制防止死循环
		$payInfo = curl_exec($curls); //执行操作
		// $err = curl_error($curls);//输出错误
		curl_close($curls); //关闭CURL会话
		
		 //$payInfo = (new wechatService())->post_curl_data($url,$xml);
		$payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		header("Content-type:text/html;charset=utf8");
		//Log::write($payInfo,"payInfo",true);
		if($payInfo['return_code'] !== 'SUCCESS'){
			//return json(['info' => $payInfo]);
			
			return json(['info' => $payInfo['return_msg']]);
		}else{
			
		   
			$info['trade_no'] =  $info["out_trade_no"];
			$res=Db::table("parkgatebill")->insert($info);
			
			if($res){
			    $jsApiParameters['appId'] = $payInfo['appid'];
				$jsApiParameters['timeStamp'] = time();
				$jsApiParameters['timeStamp'] = '$jsApiParameters["timeStamp"]';
				$jsApiParameters['nonceStr'] = $this->createNoncestr();
				$jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
				$jsApiParameters['signType'] = 'MD5';
				$jsApiParameters['paySign'] = $this->MakeSigns($jsApiParameters,$wxkey);
				return json(['jsApiParameters' => json_encode($jsApiParameters)]);
			}else{
				return json(['info' => '订单存储失败']);
			}
		}   
    }
    
    	//产生随机字符串，不长于32位
    private function createNoncestr($length = 32){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++)
        {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }

        return $str;
    }
	
	//生成签名
    private function MakeSign($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }
	
	//生成签名
    private function MakeSigns($arr,$wxkey){
        //签名步骤一：按字典序排序参数
        ksort($arr);
        $string = $this->ToUrlParams($arr);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . $wxkey;
        //签名步骤三：MD5加密
        $result = md5($string);
        return $result;
    }

    //输出xml字符
    private function ToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key => $val){
            if (is_numeric($val)){
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }else{
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
	    //格式化参数格式化成url参数
    private function ToUrlParams($value){
        $buff = "";
        foreach($value as $k => $v){
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }
    function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    } 
}